﻿using System;

namespace JeanFish.Common
{
    /// <summary>
    /// 枚举扩展方法
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 将指定字符串转换为枚举类型
        /// </summary>
        /// <typeparam name="EnumType">枚举类型</typeparam>
        /// <param name="value">字符串</param>
        /// <param name="ignoreCase">是否忽略大小写</param>
        /// <returns>转换后的枚举类型</returns>
        public static EnumType Parse<EnumType>(this string value, bool ignoreCase = true)
        {
            return (EnumType)Enum.Parse(typeof(EnumType), value, ignoreCase);
        }

        public static string TextValue(this Enum enumValue)
        {
            string enumValueText = enumValue.ToString();
            return enumValue.GetFieldAttribute<EnumTextValueAttribute>(enumValueText, new EnumTextValueAttribute(enumValueText)).TextValue;
        }
        public static string Description(this Enum enumValue)
        {
            string enumValueText = enumValue.ToString();
            return enumValue.GetFieldAttribute<EnumTextValueAttribute>(enumValueText, new EnumTextValueAttribute(enumValueText)).Description;
        }
    }

    [AttributeUsage(AttributeTargets.Field)]
    public class EnumTextValueAttribute : Attribute
    {
        public EnumTextValueAttribute(string textValue, string description = "")
        {
            this.TextValue = textValue;
            this.Description = description;
        }
        public string TextValue
        {
            get;
            set;
        }
        public string Description
        {
            get;
            set;
        }
    }
}
